package com.siwei.apply.service.impl;

import com.siwei.apply.mapper.NodeLandMapper;
import com.siwei.apply.service.NodeLandService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 节点地块关联 服务实现类
 */
@Service
public class NodeLandImpl implements NodeLandService {
    
    private static final Logger logger = LoggerFactory.getLogger(NodeLandImpl.class);
    
    @Autowired
    private NodeLandMapper nodeLandMapper;
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void createNodeLand(String nodeId, String geomDbId) {
        try {
            if (nodeId == null || nodeId.trim().isEmpty()) {
                logger.warn("创建节点地块关联失败：nodeId不能为空");
                throw new IllegalArgumentException("nodeId不能为空");
            }

            if (geomDbId == null || geomDbId.trim().isEmpty()) {
                logger.warn("创建节点地块关联失败：geomDbId不能为空");
                throw new IllegalArgumentException("geomDbId不能为空");
            }

            // 先删除该nodeId的所有关联记录
            nodeLandMapper.deleteByNodeId(nodeId);
            logger.info("删除已存在的节点地块关联记录，nodeId: {}", nodeId);

            // 创建新的关联记录
            nodeLandMapper.insertByNodeIdAndGeomDbId(nodeId, geomDbId);
            logger.info("成功创建节点地块关联记录，nodeId: {}, geomDbId: {}", nodeId, geomDbId);

        } catch (Exception e) {
            logger.error("创建节点地块关联记录异常，nodeId: {}, geomDbId: {}", nodeId, geomDbId, e);
            throw e; // 重新抛出异常以触发事务回滚
        }
    }
    
    @Override
    public Map<String, Object> getGeomByNodeId(String nodeId) {
        try {
            if (nodeId == null || nodeId.trim().isEmpty()) {
                logger.warn("查询地块几何信息失败：nodeId不能为空");
                return null;
            }

            Map<String, String> result = nodeLandMapper.selectGeomByNodeId(nodeId);
            if (result == null) {
                logger.info("未查询到地块几何信息，nodeId: {}", nodeId);
                return null;
            }

            // 调试日志：打印从数据库返回的原始数据
            logger.info("数据库返回的原始数据: {}", result);
            logger.info("geomDbId的值: {}", result.get("geomDbId"));

            // 处理返回数据格式
            Map<String, Object> response = new HashMap<>();

            // 添加geomDbId - 单个值
            response.put("geomDbId", result.get("geomDbId"));

            // 添加shppath - SHP文件路径
            response.put("shppath", result.get("shppath"));

            // 处理geoms - 转换为字符串数组
            String geomsStr = result.get("geoms");
            if (geomsStr != null && !geomsStr.trim().isEmpty()) {
                response.put("geoms", Arrays.asList(geomsStr.split("\\|")));
            } else {
                response.put("geoms", new ArrayList<>());
            }

            // 添加envelope和centroid
            response.put("envelope", result.get("envelope"));
            response.put("centroid", result.get("centroid"));

            logger.info("查询到地块几何信息，nodeId: {}", nodeId);
            return response;

        } catch (Exception e) {
            logger.error("查询地块几何信息异常，nodeId: {}", nodeId, e);
            return null;
        }
    }
    
    @Override
    public void deleteByNodeId(String nodeId) {
        try {
            if (nodeId == null || nodeId.trim().isEmpty()) {
                logger.warn("删除节点地块关联失败：nodeId不能为空");
                throw new IllegalArgumentException("nodeId不能为空");
            }

            nodeLandMapper.deleteByNodeId(nodeId);
            logger.info("删除节点地块关联记录，nodeId: {}", nodeId);

        } catch (Exception e) {
            logger.error("删除节点地块关联记录异常，nodeId: {}", nodeId, e);
            throw e;
        }
    }

    @Override
    public Map<String, Object> getGeomByProjectAndNodeTable(String projectId, String nodeTableName) {
        try {
            if (projectId == null || projectId.trim().isEmpty()) {
                logger.warn("根据项目与节点表名查询失败：projectId不能为空");
                return null;
            }
            if (nodeTableName == null || nodeTableName.trim().isEmpty()) {
                logger.warn("根据项目与节点表名查询失败：nodeTableName不能为空");
                return null;
            }
            String nodeId = nodeLandMapper.selectNodeIdsByProjectIdAndNodeTableName(projectId, nodeTableName);
            if (nodeId == null || nodeId.trim().isEmpty()) {
                logger.info("未查询到匹配的项目流程节点，projectId: {}, nodeTableName: {}", projectId, nodeTableName);
                return null;
            }
            return getGeomByNodeId(nodeId);
        } catch (Exception e) {
            logger.error("根据项目与节点表名获取地块几何信息异常，projectId: {}, nodeTableName: {}", projectId, nodeTableName, e);
            return null;
        }
    }
}
